package com.xhgj.thread;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;

/**
 * @author 周宇
 * @create 2020-06-27 12:28
 * 练习Thread实现图片 多线程下载
 */
public class PictureThread extends Thread {

    private String url;//图片地址
    private String name;//保存的图片名

    public PictureThread(String url, String name) {
        this.url = url;
        this.name = name;
    }

    //下载图片的执行体
    @Override
    public void run() {
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.downloader(url, name);
        System.out.println("下载了文件名为：" + name);
    }

    public static void main(String[] args) {
        PictureThread p1 = new PictureThread("https://cdn2.jianshu.io/assets/default_avatar/2-9636b13945b9ccf345bc98d0d81074eb.jpg", "1.jpg");
        PictureThread p2 = new PictureThread("http://seopic.699pic.com/photo/50163/5313.jpg_wh1200.jpg", "2.jpg");
        PictureThread p3 = new PictureThread("https://highpic.originoo.com/highpic/detail/161025/RM/bji81201635.jpg", "3.jpg");

        p1.start();
        p2.start();
        p3.start();
    }
}

//下载器
class WebDownloader {
    //下载方法
    public void downloader(String url, String name) {
        try {
            FileUtils.copyURLToFile(new URL(url), new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO异常，downloader方法出现问题");
        }
    }
}